package com.nine.mymall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.nine.common.constant.ProductConstant;
import com.nine.common.to.es.SkuEsModel;
import com.nine.common.utils.R;
import com.nine.mymall.search.config.MyMallElasticSearchConfig;
import com.nine.mymall.search.constant.EsConstant;
import com.nine.mymall.search.fegin.ProductFeginService;
import com.nine.mymall.search.service.MallSearchService;
import com.nine.mymall.search.vo.AttrResponseVo;
import com.nine.mymall.search.vo.SearchParam;
import com.nine.mymall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.tomcat.util.security.Escape;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: duonine
 * @date: 2021/11/11
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {


    // es操作
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeginService productFeginService;

    /**
     * es中进行检索
     *
     * @param param
     * @return
     */
    @Override
    public SearchResult search(SearchParam param) {
        // 动态构建查询需要的DSL语句
        SearchResult result = new SearchResult();
        // 1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            // 2、执行检索请求
            SearchResponse response = client.search(searchRequest, MyMallElasticSearchConfig.COMMON_OPTIONS);
            // 3、分析响应数据
            result = buildSearchResult(param, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 准备检索请求
     * <p>
     * 模糊匹配、过滤（属性、分类、品牌、价格区间、库存）、排序、分页、高亮、聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {

        // 构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /**
         * 模糊匹配、过滤（属性、分类、品牌、价格区间、库存）
         */
        // 1、构建bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1、must-模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 1.2、bool-filter-三级分类id
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 1.3、bool-filter-品牌id
        if (param.getBrandId() != null) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }

        // 1.4、bool-filter-按照属性查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            // attrs=1_5寸:8寸&attrs=2_16G:8G
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
                String[] attr_vals = attrStr.split("_");
                String attrId = attr_vals[0];   // 检索的属性id
                String[] attrValues = attr_vals[1].split(":");   // 检索的属性values

                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));

                // attrs有多个，在循环中调用
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", queryBuilder, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }


        // 1.5、bool-filter-按照库存查询
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        // 1.6、bool-filter-按照价格区间，skuPrice=1_500/_500/500_
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            String[] skuPrices = param.getSkuPrice().split("_");
            if (skuPrices.length == 2) {
                rangeQuery.gte(skuPrices[0]).lte(skuPrices[1]);
            } else if (skuPrices.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(skuPrices[1]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(skuPrices[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        sourceBuilder.query(boolQuery);
        /**
         * 排序、分页、高亮
         */

        // 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            // sort(String name, SortOrder order)
            sourceBuilder.sort(s[0], order);
        }

        // 分页`  pageSize:5
        // pageNum:1    from:0,size:5
        // pageNum:2    from:5,size:5
        // from = (pageNum-1) * pageSize
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        // 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        // 1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(10);

        // 1.1、品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        // 2、分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(1);

        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        // 3、属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

        System.out.println("页面构建的DSL语句：" + sourceBuilder.toString());

        // 有参构造方法：SearchRequest(String[] indices, SearchSourceBuilder source)
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 分析响应数据
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchParam param, SearchResponse response) {
        SearchResult result = new SearchResult();

        // 命中数据
        SearchHits hits = response.getHits();
        // 聚合数据
        Aggregations aggregations = response.getAggregations();

        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);

                // 处理高亮信息
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }

                esModels.add(skuEsModel);
            }
        }
        // 1、返回的所有商品信息
        result.setProduct(esModels);

        // 2、返回的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brand_agg.getBuckets();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            long brandId = brandAggBucket.getKeyAsNumber().longValue();
            // 品牌id
            brandVo.setBrandId(brandId);
            // 品牌名称
            ParsedStringTerms brand_name_agg = brandAggBucket.getAggregations().get("brand_name_agg");
            String brand_name = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brand_name);

            // 品牌图片
            ParsedStringTerms brand_img_agg = brandAggBucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        // 3、返回的所有分类信息 (Ctrl+H)
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> catalogAggBuckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : catalogAggBuckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));

            // 分类名称
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);

            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        // 4、返回的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = aggregations.get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrIdAggBuckets = attr_id_agg.getBuckets();
        for (Terms.Bucket attrIdAggBucket : attrIdAggBuckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();

            // 属性id
            long attrId = attrIdAggBucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            // 属性名称
            ParsedStringTerms attr_name_agg = attrIdAggBucket.getAggregations().get("attr_name_agg");
            String attr_name = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attr_name);

            // 属性值
            ParsedStringTerms attr_value_agg = attrIdAggBucket.getAggregations().get("attr_value_agg");
            List<? extends Terms.Bucket> attrValueAggBuckets = attr_value_agg.getBuckets();
            List<String> attrValues = attrValueAggBuckets.stream().map(item -> {
                return ((Terms.Bucket) item).getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        // 5、分页信息

        // 当前页码
        result.setPageNum(param.getPageNum());

        // 总记录数
        TotalHits totalHits = hits.getTotalHits();
        long total = totalHits.value;
        result.setTotal(total);

        // 总页码
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);

        // 页码集合
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);


        // 面包屑导航数据
        List<SearchResult.NavVo> navVos = new ArrayList<>();

        List<String> attrs = param.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            navVos = attrs.stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                // attr=2_5寸:6寸
                String[] attr_arr = attr.split("_");
                navVo.setNavValue(attr_arr[1]);


                // 所有已有的attrId值
                result.getAttrIds().add(Long.parseLong(attr_arr[0]));

                R r = productFeginService.attrInfo(Long.parseLong(attr_arr[0]));

                if (r.getCode() == 0) {
                    AttrResponseVo responseVo = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(responseVo.getAttrName());
                } else {
                    navVo.setNavName(attr_arr[0]);
                }
                // 取消面包屑，跳转到哪边？将请求地址的url替换掉
                String replaceAttr = replaceQueryString(param, attr, "attrs");
                navVo.setLink("http://search.mymall.com/list.html?" + replaceAttr);

                return navVo;
            }).collect(Collectors.toList());
        }
        result.setNavs(navVos);

        // 品牌信息
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");

            // 远程查询所有品牌
            R r = productFeginService.brandInfos(param.getBrandId());
            if (r.getCode() == 0) {
                List<SearchResult.BrandVo> brands = r.getData("brands", new TypeReference<List<SearchResult.BrandVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String repalce = "";
                for (SearchResult.BrandVo brand : brands) {
                    buffer.append(brand.getBrandName() + ";");
                    repalce = replaceQueryString(param, brand.getBrandId() + "", "brandId");
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.mymall.com/list.html?" + repalce);
            }
            navVos.add(navVo);
        }

        // TODO 分类

        return result;
    }

    private String replaceQueryString(SearchParam param, String value, String key) {
        String encodeAttr = null;
        try {
            encodeAttr = URLEncoder.encode(value, "UTF-8");
            // 浏览器对空格的编码和java不一样
            encodeAttr.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace("&" + key + "=" + encodeAttr, "");
    }

}
